from flask import Blueprint, render_template, redirect, url_for, flash, request
from flask_login import login_user, logout_user, login_required, current_user
from werkzeug.security import generate_password_hash, check_password_hash

from app.models.user import User

auth_bp = Blueprint('auth', __name__)


@auth_bp.route('/login', methods=['GET', 'POST'])
def login():
    if current_user.is_authenticated:
        return redirect(url_for('main.index'))
    
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')
        remember = request.form.get('remember', 'off') == 'on'
        
        user = User.find_by_username(username)
        
        if user and user.check_password(password):
            login_user(user, remember=remember)
            next_page = request.args.get('next')
            flash('登录成功！', 'success')
            return redirect(next_page or url_for('main.index'))
        else:
            flash('登录失败，请检查用户名和密码！', 'danger')
    
    return render_template('auth/login.html')


@auth_bp.route('/register', methods=['GET', 'POST'])
def register():
    if current_user.is_authenticated:
        return redirect(url_for('main.index'))
    
    if request.method == 'POST':
        username = request.form.get('username')
        email = request.form.get('email')
        password = request.form.get('password')
        password_confirm = request.form.get('password_confirm')
        
        error = None
        if not username:
            error = '用户名不能为空'
        elif not email:
            error = '邮箱地址不能为空'
        elif not password:
            error = '密码不能为空'
        elif password != password_confirm:
            error = '两次输入的密码不一致'
        elif User.find_by_username(username):
            error = f'用户名 {username} 已被注册'
        elif User.find_by_email(email):
            error = f'邮箱 {email} 已被注册'
        
        if error is None:
            user = User(username=username, email=email, password=password)
            user.save()
            flash('注册成功，请登录！', 'success')
            return redirect(url_for('auth.login'))
        
        flash(error, 'danger')
    
    return render_template('auth/register.html')


@auth_bp.route('/logout')
@login_required
def logout():
    logout_user()
    flash('您已成功退出登录！', 'success')
    return redirect(url_for('main.index'))


@auth_bp.route('/reset-password', methods=['GET', 'POST'])
def reset_password():
    return render_template('auth/reset_password.html')